import numpy as np
import os, shutil
from tqdm import tqdm as tqdm
import os.path as osp


def select_imgs():
    image_dir = r"H:\warship\images"
    according = r"H:\warship\masks"

    img_suffix = ".png"
    new_image_dir = image_dir + "_new"
    os.makedirs(new_image_dir)

    for file in os.listdir(according):
        img_path = os.path.join(image_dir, file.replace('.json', img_suffix))
        new_path = os.path.join(new_image_dir, file.replace('.json', img_suffix))
        shutil.copy(img_path, new_path)


def cp_image_with_reference():
    "如果需要参照一个文件夹里文件的名称，然后把数据从一个文件夹移到另一个文件夹，那就用这个脚本"
    ref_dir = r"/Users/edy/Downloads/Annotations_new"
    dst_dir = r"/Users/edy/Data/yq1-0-show/yq1_0_show_data_mix_dp/dp_mix_split_ten_dp/second_train/foldv1/val"
    origin_dir = r"/Users/edy/Data/yq1-0-show/yq1_0_show_data_mix_dp/dp_mix_split_ten_dp/second_train/raw_data/Annotations"

    ref_dir = r"/Users/edy/Data/DB/yq10_db/data_split/data_foldv1_378/images/train"
    dst_dir = r"/Users/edy/Data/DB/yq10_db/data_split/data_foldv1_378/images/JPEGImages"
    origin_dir = r"/Users/edy/Data/DB/yq10_db/JPEGImages"

    os.makedirs(dst_dir,exist_ok=True)
    # 参照的文件名后缀
    suffix = '.jpg'

    reference_files = [x.split(suffix)[0] for x in list(filter(lambda x: x.endswith(suffix), os.listdir(ref_dir)))]
    origin_files = os.listdir(origin_dir)

    for file in tqdm(origin_files):
        # if file.split('.')[0] in reference_files:
        if file.split('.')[0] not in reference_files:
            if not os.path.exists(osp.join(dst_dir, file)):
                shutil.copy(osp.join(origin_dir, file), osp.join(dst_dir, file))
                # shutil.move(osp.join(origin_dir, file), osp.join(dst_dir, file))

def cp_from_txt():
    txt_path=r"/Users/edy/Data/DB/actual/test/record.txt"
    dst_dir=r"/Users/edy/Data/DB/actual/test/810_2"

    os.makedirs(dst_dir,exist_ok=True)
    with open(txt_path,'r',encoding='utf-8') as f:
        record=f.readlines()
    record=[x.strip('\n') for x in record]

    for file in tqdm(record):
        shutil.copy(file,osp.join(dst_dir,osp.basename(file)))


def merge_multi_dir():
    "把多个文件夹下的文件弄到一个文件夹"
    root_path=r"/Users/edy/Data/DB/actual/test/2021-08-10"
    dst_path=osp.join(osp.dirname(root_path),"%s_%s"%(osp.basename(root_path),'merged_dir'))
    os.makedirs(dst_path,exist_ok=True)

    for dir in os.listdir(root_path):
        dir_path=osp.join(root_path,dir)
        if osp.isdir(dir_path):
            for file in os.listdir(dir_path):
                shutil.copy(osp.join(dir_path,file),osp.join(dst_path,file))

def main():
    # select_imgs()
    cp_image_with_reference()
    # cp_from_txt()
    # merge_multi_dir()

main()
